package xiaobange.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xiaobange.common.CustomException;
import xiaobange.common.R;
import xiaobange.entity.User;
import xiaobange.service.UserService;
import xiaobange.utils.SendEMail;
import xiaobange.utils.ValidateCodeUtils;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取验证码
     * @param user
     * @param httpSession
     * @return
     */
    @PostMapping("sendMsg")
    public R<String> RadCode(@RequestBody User user, HttpSession httpSession){
        if (user.getPhone() != null){
            //生成验证码
            Integer Ram = ValidateCodeUtils.generateValidateCode(4);
            //发送邮件
            try {
                SendEMail.AddEMali(user.getPhone(), String.valueOf("【能力有限公司】您的验证码是："+Ram +",有效时间为5分钟，请尽快输入。如非本人操作，请忽略本消息。"));
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
            //吧验证码保存到session里
            //httpSession.setAttribute("phone",Ram);
            //把验证码存到Redis是中，有效期五分钟
            redisTemplate.opsForValue().set(user.getPhone(), Ram.toString(),5, TimeUnit.MINUTES);
            log.info("验证码是：{}",Ram);
            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");
    }


    /**
     *登录
     * @param map
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/login")
    public R<String> LongCheck(@RequestBody Map map , HttpServletRequest httpServletRequest){
        //获取用户的手机号
        String u_phone = map.get("phone").toString();
        //获取用户输入的验证码
        String u_code = map.get("code").toString();
        //存入session的获取验证码   2022-12-21改：验证码从Redis中获取
        HttpSession session = httpServletRequest.getSession();
        //获取存到Redis中的验证码
        String RedisRam = (String) redisTemplate.opsForValue().get(u_phone);

        /*String sionRam = null;
        try {
            sionRam = RedisRam.getAttribute("phone").toString();
        } catch (Exception e) {
            throw new CustomException("验证码错误");
        }*/

        //判断用户输入的验证码是否相同
        if (u_code != null && u_code.equals(RedisRam)){
            //判断用户是否已经完成注册
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone , u_phone);
            User user = userService.getOne(lambdaQueryWrapper);
            //如果用户不存在那么就自动帮他注册
            if (user == null){
                user = new User();
                user.setPhone(u_phone);
                user.setStatus(1);
                userService.save(user);
            }
            //删除Redis里的验证码
            redisTemplate.delete(u_phone);
            //吧用户的信息存入session
            session.setAttribute("user",user.getId());
            return R.success("登录成功");
        }

        return R.error("验证码错误！");
    }

    /**
     * 退出请求
     * @param httpSession
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession httpSession){
        httpSession.removeAttribute("user");
        return R.success("退出成功");
    }


}
